﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Project
{
    /// <summary>
    /// Interaction logic for PrintPreviewDialog.xaml
    /// </summary>
    public partial class PrintPreviewDialog : Window
    {
        private UIElement _element;

        public PrintPreviewDialog(UIElement element)
        {
            InitializeComponent();
            _element = element;
            RenderImage();
        }

        public void RenderImage()
        {
            Image myImage = new Image();
            FormattedText text = new FormattedText("ABC",
                    new CultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new FontStretch()),
                    this.FontSize,
                    this.Foreground);

            RenderTargetBitmap bmp;
            if(_element is Grid)
            {
                bmp = new RenderTargetBitmap((int) (_element as Grid).ActualWidth, (int) (_element as Grid).ActualHeight, 80, 80,
                                      PixelFormats.Pbgra32);
                bmp.Render(_element);
                myImage.Source = bmp;
                ControlPreview.Height = (int)(_element as Grid).ActualHeight * 0.45;
                ControlPreview.Width = (int)(_element as Grid).ActualWidth * 0.45;
            }
            if(_element is UserControl)
            {
                bmp = new RenderTargetBitmap((int) (_element as UserControl).ActualWidth, (int) (_element as UserControl).ActualHeight, 80, 80,
                                      PixelFormats.Pbgra32);
                bmp.Render(_element);
                myImage.Source = bmp;
                ControlPreview.Height = (int)(_element as UserControl).ActualHeight * 0.45;
                ControlPreview.Width = (int)(_element as UserControl).ActualWidth * 0.45;
            }
            
            ControlPreview.Source = myImage.Source;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            if ((bool)pd.ShowDialog().GetValueOrDefault())
            {
                pd.PrintVisual((UIElement)_element, "Printing document");
            }
        }
    }
}
